package com.jier.common.interceptor;

import com.jier.common.util.PropertiesUtil;
import com.jier.entities.SystemLog;
import com.jier.entities.SystemUser;
import com.jier.service.ISystemLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 后台登陆拦截
 *
 * @author jie_r
 * @date 2016/9/22
 */
@Component
public class AdminInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private ISystemLogService systemLogService;

    private SystemUser user;

    private static String LOGIN;

    {
        try {
            LOGIN = PropertiesUtil.getResStr("project.admin.page.login");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String webRoot = request.getServletContext().getContextPath();
        HttpSession session = request.getSession();
        if (session == null) {
            response.sendRedirect(webRoot + LOGIN);
            return false;
        }
        user = (SystemUser) session.getAttribute("currentUser");
        if (user == null) {
            response.sendRedirect(webRoot + LOGIN);
            return false;
        }
        return true;
    }

    /**
     * 请求完成后，保存日志
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (request.getHeader("accept").contains("text/html")) {
            SystemLog systemLog = new SystemLog();
            systemLog.setSystemUserId(user.getId());
            Object content = request.getAttribute("content");
            if (content == null) {
                content = request.getRequestURI();
            }
            systemLog.setContent("请求页面：" + content);
            systemLog.setHttpStatus(response.getStatus());
            // 获取错误信息
            getErrorMsg(systemLog, request);
            systemLogService.save(systemLog);
        }
        if (request.getHeader("accept").contains("application/json")) {
            SystemLog systemLog = new SystemLog();
            systemLog.setSystemUserId(user.getId());
            Object content = request.getAttribute("content");
            if (content == null) {
                content = request.getRequestURI();
            }
            systemLog.setContent("请求数据：" + content);
            systemLog.setHttpStatus(response.getStatus());
            // 获取错误信息
            getErrorMsg(systemLog, request);
            systemLogService.save(systemLog);
        }
        super.afterCompletion(request, response, handler, ex);
    }

    /**
     * 提取错误信息
     *
     * @param systemLog
     * @param request
     * @return
     */
    public SystemLog getErrorMsg(SystemLog systemLog, HttpServletRequest request) throws Exception {
        String httpStatus = String.valueOf(systemLog.getHttpStatus());
        // 请求状态为2xx 或者 3xx 为正常请求
        if (httpStatus.startsWith("2") || httpStatus.startsWith("3")) {
            systemLog.setStatus(Boolean.TRUE);
        } else {
            systemLog.setStatus(Boolean.FALSE);
            Object error = request.getAttribute("error");
            if (error == null) {
                systemLog.setError("服务器出错");
            } else {
                systemLog.setError(error.toString());
            }
        }
        systemLog.setUpdateDate(new Date());
        systemLog.setCreateDate(new Date());
        return systemLog;
    }

}
